/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.sim.controller;

import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.constants.ErrorCode;
import cn.iot.card.open.context.LoginContextHolder;
import cn.iot.card.open.context.model.LoginUser;
import cn.iot.card.open.exception.enums.BizExceptionEnum;
import cn.iot.card.open.modular.entity.AccountCard;
import cn.iot.card.open.modular.entity.Card;
import cn.iot.card.open.modular.entity.UserGroupRl;
import cn.iot.card.open.modular.log.ApiBussinessLog;
import cn.iot.card.open.modular.service.AccountCardService;
import cn.iot.card.open.modular.service.CardService;
import cn.iot.card.open.modular.service.UserService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.pojo.page.LayuiPageInfo;
import cn.iot.card.open.sim.dto.general.SimAPNFunctionDTO;
import cn.iot.card.open.sim.dto.general.SimCommunicationFunctionDTO;
import cn.iot.card.open.sim.dto.general.SimFunctionDTO;
import cn.iot.card.open.sim.dto.siminfo.GprsPccFunctionDTO;
import cn.iot.card.open.sim.service.GeneralCommunicateService;
import cn.iot.card.open.util.CommonUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物联卡综合信息-通信
 *
 * @author 何光鑫
 * @date 20200326 11:00:48
 * @modify 20200326 何光鑫 v1.1.2.1 创建
 * @since v1.1.2.1
 */
@Controller
@RequestMapping("/generalCommunicate")
public class GeneralCommunicateController {

    /**
     * 页面路径前缀
     */
    private static String PREFIX = "/modular/sim/general/communicate/";

    @Autowired
    private GeneralCommunicateService generalCommunicateService;

    @Autowired
    private CardService cardService;

    @Autowired
    private UserService userService;

    @Autowired
    private AccountCardService accountCardService;

    /**
     * 通信功能开通状态
     *
     * @param msisdn 物联卡号码
     * @param iccid 集成电路卡识别码
     * @param imsi 国际移动用户识别码
     * @return 返回 layui page info
     * @throws IOException  
     * @author 何光鑫
     * @date 20200326 11:00:48
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/queryCommunicateFunctionStatus")
    @ResponseBody
    public LayuiPageInfo queryCommunicateFunctionStatus(@RequestParam(required = false) String msisdn, @RequestParam(required = false) String iccid, @RequestParam(required = false) String imsi) throws IOException {
        Map<String, Object> map = new HashMap<>();
        String cardType = "";
        String cardNum = "";
        if(ToolUtil.isNotEmpty(msisdn)){
            map.put(Constants.REQUEST_PARAM_MSISDN,msisdn);
            cardType = Constants.REQUEST_PARAM_MSISDN;
            cardNum = msisdn;
        }else if(ToolUtil.isNotEmpty(iccid)){
            map.put(Constants.REQUEST_PARAM_ICCID,iccid);
            cardType = Constants.REQUEST_PARAM_ICCID;
            cardNum = iccid;
        }else if(ToolUtil.isNotEmpty(imsi)){
            map.put(Constants.REQUEST_PARAM_IMSI,imsi);
            cardType = Constants.REQUEST_PARAM_IMSI;
            cardNum = imsi;
        }else{
            return LayuiPageFactory.createEmptyPageInfo();
        }
        map.put(Constants.RESPONSE_DELETED,Constants.RESPONSE_DELETED_FALSE);
        List<Card> cards = cardService.getBaseMapper().selectByMap(map);
        if(ToolUtil.isEmpty(cards)){
            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        Card card = cards.get(0);
        // 验证当前用户是否有卡权限
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }
        Map<String, Object> cardDtoMap = cardService.getCardInfo(card.getCardId());
        Object accountIdObj = cardDtoMap.get(Constants.REQUEST_ACCOUNT_ID);
        if (ToolUtil.isEmpty(accountIdObj)) {
            // 当前卡未绑定任何账户
            return LayuiPageFactory.cteateErrorMsg(ErrorCode.ERR11047);
        }
        String accountId = String.valueOf(accountIdObj);
        String transId = CommonUtil.generateTransId(String.valueOf(accountId));
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(cardType,cardNum);
        return generalCommunicateService.queryCommunicateFunctionStatus(transId,accountId,parameterMap);
    }

    /**
     * 跳转到基础功能开停界面
     *
     * @return 返回 string  
     * @author 何光鑫
     * @date 20200326 19:40:45
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/toSimCommunicationFunctionBatch")
    public String toSimCommunicationFunctionBatch() {
        return PREFIX + "simCommunicationFunctionBatch.html";
    }


    /**
     * 基础功能开停
     *
     * @param simCommunicationFunctionDTO 物联卡通信功能开停请求参数
     * @return 返回 response data
     * @throws Exception  
     * @author 何光鑫
     * @date 20200326 19:40:45
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/simCommunicationFunctionBatch")
    @ApiBussinessLog(value = "物联卡基础通信功能开停")
    @ResponseBody
    public ResponseData simCommunicationFunctionBatch(SimCommunicationFunctionDTO simCommunicationFunctionDTO) throws Exception {
        String msisdns = simCommunicationFunctionDTO.getMsisdns();
        Card card = cardService.findCard(Constants.REQUEST_PARAM_MSISDN, msisdns);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());

        String transId = CommonUtil.generateTransId(accountId);
        String serviceType = simCommunicationFunctionDTO.getServiceType();
        String operType = simCommunicationFunctionDTO.getOperType();
        String apnName = simCommunicationFunctionDTO.getApnName();
        return generalCommunicateService.simCommunicationFunctionBatch(transId,accountId,msisdns,serviceType,operType,apnName);
    }

    /**
     * 跳转APN功能开停页面
     *
     * @return 返回 string
     * @author zhanlele
     * @date 20200312 21:19:48
     * @modify 20200312 zhanlele v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/toOperateApnFunction")
    public String toOperateApnFunction() {
        return PREFIX + "operateApnFunction.html";
    }

    /**
     * APN功能开停
     *
     * @param simAPNFunctionDTO 单卡APN功能开停请求参数
     * @return 返回 response data
     * @throws Exception  
     * @author 何光鑫
     * @date 20200326 19:06:22
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/operateApnFunction")
    @ApiBussinessLog(value = "物联卡APN功能开停")
    @ResponseBody
    public ResponseData operateApnFunction(SimAPNFunctionDTO simAPNFunctionDTO)throws Exception {
        String cardType = simAPNFunctionDTO.getCardType();
        String cardNum = simAPNFunctionDTO.getCardNum();
        Card card = cardService.findCard(cardType,cardNum);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());
        String transId = CommonUtil.generateTransId(accountId);
        String apnName = simAPNFunctionDTO.getApnName();
        String operType = simAPNFunctionDTO.getOperType();
        return generalCommunicateService.operateApnFunction(transId, accountId, cardType,cardNum,apnName,operType);
    }

    /**
     * 跳转到短信功能开停界面
     *
     * @return 返回 string  
     * @author 何光鑫
     * @date 20200326 19:40:45
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/toSimSmsFunction")
    public String toSimSmsFunction() {
        return PREFIX + "simSmsFunction.html";
    }


    /**
     * 短信功能开停
     *
     * @param simFunctionDTO 单卡短信功能开停请求参数
     * @return 返回 response data
     * @throws Exception  
     * @author 何光鑫
     * @date 20200326 19:40:46
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/simSmsFunction")
    @ApiBussinessLog(value = "物联卡短信功能开停")
    @ResponseBody
    public ResponseData simSmsFunction(SimFunctionDTO simFunctionDTO) throws Exception {
        String cardType = simFunctionDTO.getCardType();
        String cardNum = simFunctionDTO.getCardNum();
        Card card = cardService.findCard(cardType, cardNum);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());

        String transId = CommonUtil.generateTransId(accountId);
        String operType = simFunctionDTO.getOperType();
        return generalCommunicateService.simSmsFunction(transId,accountId,cardType,cardNum,operType);
    }

    /**
     * 跳转到语音功能开停界面
     *
     * @return 返回 string  
     * @author 何光鑫
     * @date 20200326 19:40:46
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/toSimCallFunction")
    public String toSimCallFunction() {
        return PREFIX + "simCallFunction.html";
    }


    /**
     * 语音功能开停
     *
     * @param simFunctionDTO
     * @return 返回 response data
     * @throws Exception  
     * @author 何光鑫
     * @date 20200326 19:40:46
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/simCallFunction")
    @ApiBussinessLog(value = "物联卡语音功能开停")
    @ResponseBody
    public ResponseData simCallFunction(SimFunctionDTO simFunctionDTO) throws Exception {
        String cardType = simFunctionDTO.getCardType();
        String cardNum = simFunctionDTO.getCardNum();
        Card card = cardService.findCard(cardType, cardNum);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());

        String transId = CommonUtil.generateTransId(accountId);
        String operType = simFunctionDTO.getOperType();
        return generalCommunicateService.simCallFunction(transId,accountId,cardType,cardNum,operType);
    }

    /**
     * 跳转到数据通信服务（PCC策略）开停界面
     *
     * @return 返回 string  
     * @author 何光鑫
     * @date 20200326 19:40:46
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/toSimGprsPccFunctionBatch")
    public String toSimGprsPccFunctionBatch() {
        return PREFIX + "simGprsPccFunctionBatch.html";
    }


    /**
     * 数据通信服务（PCC策略）开停
     *
     * @param gprsPccFunctionDTO 物联卡数据通信服务（PCC策略）开停请求参数
     * @return 返回 response data
     * @throws Exception  
     * @author 何光鑫
     * @date 20200326 19:40:46
     * @modify 20200326 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    @RequestMapping("/simGprsPccFunctionBatch")
    @ApiBussinessLog(value = "物联卡数据通信服务（PCC策略）开停")
    @ResponseBody
    public ResponseData simGprsPccFunctionBatch(GprsPccFunctionDTO gprsPccFunctionDTO) throws Exception {
        String msisdns = gprsPccFunctionDTO.getMsisdns();
        Card card = cardService.findCard(Constants.REQUEST_PARAM_MSISDN, msisdns);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());

        String transId = CommonUtil.generateTransId(accountId);
        String apnName = gprsPccFunctionDTO.getApnName();
        String pccCode = gprsPccFunctionDTO.getPccCode();
        String operType = gprsPccFunctionDTO.getOperType();
        return generalCommunicateService.simGprsPccFunctionBatch(transId,accountId,msisdns,apnName,pccCode,operType);
    }
}
